<!--
  成绩分析页面
-->
<template>
  <div class="grade-analysis">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>成绩分析</h1>
        <p>深度分析考试成绩数据和趋势</p>
      </div>
      <div class="header-right">
        <el-button
          :icon="Download"
          @click="exportAnalysisReport"
        >
          导出报告
        </el-button>
      </div>
    </div>

    <!-- 分析控制面板 -->
    <el-card class="control-panel">
      <div class="panel-content">
        <div class="control-section">
          <h4>分析范围</h4>
          <el-form :model="analysisConfig" label-width="80px" size="small">
            <el-form-item label="考试">
              <el-select
                v-model="analysisConfig.examinationId"
                placeholder="选择考试"
                @change="handleExamChange"
                style="width: 250px"
              >
                <el-option
                  v-for="exam in examinationList"
                  :key="exam.id"
                  :label="exam.title"
                  :value="exam.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="班级">
              <el-select
                v-model="analysisConfig.classId"
                placeholder="选择班级"
                clearable
                @change="handleClassChange"
                style="width: 150px"
              >
                <el-option
                  v-for="className in classList"
                  :key="className"
                  :label="className"
                  :value="className"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <div class="control-section">
          <h4>分析维度</h4>
          <el-checkbox-group v-model="analysisConfig.dimensions" @change="handleAnalysisChange">
            <el-checkbox label="score_distribution">分数分布</el-checkbox>
            <el-checkbox label="class_comparison">班级对比</el-checkbox>
            <el-checkbox label="question_analysis">题目分析</el-checkbox>
            <el-checkbox label="difficulty_analysis">难度分析</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="control-section">
          <el-button type="primary" :icon="Search" @click="refreshAnalysis" :loading="analysisLoading">
            刷新分析
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 分析内容区域 -->
    <div v-if="analysisData" class="analysis-content">
      <!-- 分数分布 -->
      <el-card v-if="analysisConfig.dimensions.includes('score_distribution')" class="analysis-card">
        <div class="card-header">
          <h3>分数分布</h3>
          <div class="chart-actions">
            <el-radio-group v-model="chartType.scoreDistribution" size="small">
              <el-radio-button label="histogram">直方图</el-radio-button>
              <el-radio-button label="pie">饼图</el-radio-button>
              <el-radio-button label="line">曲线图</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div id="scoreDistributionChart" class="chart-container"></div>
        <div class="chart-stats">
          <div class="stat-item">
            <div class="stat-value">{{ scoreStats.average }}</div>
            <div class="stat-label">平均分</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ scoreStats.median }}</div>
            <div class="stat-label">中位数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ scoreStats.stdDeviation }}</div>
            <div class="stat-label">标准差</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ scoreStats.passRate }}%</div>
            <div class="stat-label">及格率</div>
          </div>
        </div>
      </el-card>

      <!-- 班级对比 -->
      <el-card v-if="analysisConfig.dimensions.includes('class_comparison')" class="analysis-card">
        <div class="card-header">
          <h3>班级对比</h3>
          <div class="chart-actions">
            <el-radio-group v-model="chartType.classComparison" size="small">
              <el-radio-button label="bar">柱状图</el-radio-button>
              <el-radio-button label="radar">雷达图</el-radio-button>
              <el-radio-button label="table">表格</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div id="classComparisonChart" class="chart-container"></div>
        <div v-if="chartType.classComparison === 'table'" class="class-comparison-table">
          <el-table :data="classComparisonData">
            <el-table-column label="班级" prop="className" />
            <el-table-column label="人数" prop="studentCount" />
            <el-table-column label="平均分" prop="averageScore" />
            <el-table-column label="最高分" prop="maxScore" />
            <el-table-column label="最低分" prop="minScore" />
            <el-table-column label="及格率" prop="passRate">
              <template #default="{ row }">
                <el-progress :percentage="row.passRate" :color="getPassRateColor(row.passRate)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <!-- 趋势分析 -->
      <el-card v-if="analysisConfig.dimensions.includes('trend_analysis')" class="analysis-card">
        <div class="card-header">
          <h3>成绩趋势</h3>
          <div class="chart-actions">
            <el-select v-model="chartType.trendAnalysis" size="small" style="width: 120px">
              <el-option label="折线图" value="line" />
              <el-option label="面积图" value="area" />
              <el-option label="柱状图" value="bar" />
            </el-select>
            <el-select v-model="trendMetric" size="small" style="width: 120px">
              <el-option label="平均分" value="average" />
              <el-option label="及格率" value="passRate" />
              <el-option label="标准差" value="stdDeviation" />
            </el-select>
          </div>
        </div>
        <div id="trendChart" class="chart-container"></div>
      </el-card>

      <!-- 题目分析 -->
      <el-card v-if="analysisConfig.dimensions.includes('question_analysis')" class="analysis-card">
        <div class="card-header">
          <h3>题目分析</h3>
          <div class="chart-actions">
            <el-select v-model="chartType.questionAnalysis" size="small" style="width: 120px">
              <el-option label="得分率" value="scoreRate" />
              <el-option label="错误率" value="errorRate" />
              <el-option label="用时" value="timeSpent" />
            </el-select>
          </div>
        </div>
        <div id="questionAnalysisChart" class="chart-container"></div>
        <div class="question-stats">
          <div class="stat-item">
            <div class="stat-value">{{ questionStats.totalQuestions }}</div>
            <div class="stat-label">总题数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ questionStats.averageCorrectRate }}%</div>
            <div class="stat-label">平均正确率</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ questionStats.hardestQuestion }}</div>
            <div class="stat-label">最难题目</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ questionStats.easiestQuestion }}</div>
            <div class="stat-label">最简单题目</div>
          </div>
        </div>
      </el-card>

      <!-- 难度分析 -->
      <el-card v-if="analysisConfig.dimensions.includes('difficulty_analysis')" class="analysis-card">
        <div class="card-header">
          <h3>难度分析</h3>
          <div class="chart-actions">
            <el-radio-group v-model="chartType.difficultyAnalysis" size="small">
              <el-radio-button label="distribution">分布图</el-radio-button>
              <el-radio-button label="heatmap">热力图</el-radio-button>
              <el-radio-button label="comparison">对比图</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div id="difficultyAnalysisChart" class="chart-container"></div>
        <div class="difficulty-stats">
          <div class="stat-item">
            <div class="stat-value easy">{{ difficultyStats.easy }}%</div>
            <div class="stat-label">简单</div>
          </div>
          <div class="stat-item">
            <div class="stat-value medium">{{ difficultyStats.medium }}%</div>
            <div class="stat-label">中等</div>
          </div>
          <div class="stat-item">
            <div class="stat-value hard">{{ difficultyStats.hard }}%</div>
            <div class="stat-label">困难</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ difficultyStats.average }}%</div>
            <div class="stat-label">平均难度</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分析结果 -->
    <div v-if="!analysisLoading && analysisConfig.examinationId" class="analysis-results">
      <!-- 分数分布分析 -->
      <el-card class="analysis-card">
        <div class="card-header">
          <h3>分数分布分析</h3>
          <div class="chart-actions">
            <el-radio-group v-model="chartType.scoreDistribution" size="small">
              <el-radio-button label="histogram">直方图</el-radio-button>
              <el-radio-button label="line">趋势图</el-radio-button>
              <el-radio-button label="pie">饼图</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div id="scoreDistributionChart" class="chart-container"></div>
        <div class="distribution-stats">
          <div class="stat-item">
            <div class="stat-value average">{{ scoreStats.average }}</div>
            <div class="stat-label">平均分</div>
          </div>
          <div class="stat-item">
            <div class="stat-value median">{{ scoreStats.median }}</div>
            <div class="stat-label">中位数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value std-dev">{{ scoreStats.stdDev }}</div>
            <div class="stat-label">标准差</div>
          </div>
          <div class="stat-item">
            <div class="stat-value pass-rate">{{ scoreStats.passRate }}%</div>
            <div class="stat-label">及格率</div>
          </div>
        </div>
      </el-card>

      <!-- 班级对比分析 -->
      <el-card class="analysis-card">
        <div class="card-header">
          <h3>班级对比分析</h3>
          <div class="chart-actions">
            <el-radio-group v-model="chartType.classComparison" size="small">
              <el-radio-button label="bar">柱状图</el-radio-button>
              <el-radio-button label="radar">雷达图</el-radio-button>
              <el-radio-button label="table">表格</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div id="classComparisonChart" class="chart-container"></div>
      </el-card>

      <!-- 题目难度分析 -->
      <el-card class="analysis-card">
        <div class="card-header">
          <h3>难度分析</h3>
          <div class="chart-actions">
            <el-radio-group v-model="chartType.difficultyAnalysis" size="small">
              <el-radio-button label="distribution">分布图</el-radio-button>
              <el-radio-button label="heatmap">热力图</el-radio-button>
              <el-radio-button label="comparison">对比图</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div id="difficultyAnalysisChart" class="chart-container"></div>
        <div class="difficulty-stats">
          <div class="stat-item">
            <div class="stat-value easy">{{ difficultyStats.easy }}%</div>
            <div class="stat-label">简单</div>
          </div>
          <div class="stat-item">
            <div class="stat-value medium">{{ difficultyStats.medium }}%</div>
            <div class="stat-label">中等</div>
          </div>
          <div class="stat-item">
            <div class="stat-value hard">{{ difficultyStats.hard }}%</div>
            <div class="stat-label">困难</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ difficultyStats.average }}%</div>
            <div class="stat-label">平均难度</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <div v-else-if="!analysisLoading" class="empty-state">
      <el-empty
        description="请选择考试进行成绩分析"
        :image-size="200"
      >
        <template #image>
          <el-icon size="100" color="#c0c4cc">
            <DataAnalysis />
          </el-icon>
        </template>
      </el-empty>
    </div>

    <!-- 加载状态 -->
    <div v-else class="loading-state">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 导出报告对话框 -->
    <el-dialog
      v-model="showExportDialog"
      title="导出分析报告"
      width="500px"
    >
      <el-form :model="exportForm" label-width="100px">
        <el-form-item label="报告格式">
          <el-radio-group v-model="exportForm.format">
            <el-radio value="pdf">PDF</el-radio>
            <el-radio value="excel">Excel</el-radio>
            <el-radio value="word">Word</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="包含内容">
          <el-checkbox-group v-model="exportForm.includeContent">
            <el-checkbox label="summary">数据摘要</el-checkbox>
            <el-checkbox label="charts">图表分析</el-checkbox>
            <el-checkbox label="details">详细数据</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="报告标题">
          <el-input
            v-model="exportForm.title"
            placeholder="请输入报告标题"
            maxlength="100"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showExportDialog = false">取消</el-button>
        <el-button
          type="primary"
          :loading="exportLoading"
          @click="confirmExport"
        >
          确认导出
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { gradingApi, examApi } from '@/api'
import * as echarts from 'echarts'
import {
  Download,
  Search,
  Refresh,
  DataAnalysis
} from '@element-plus/icons-vue'
import type { Examination } from '@/types'

// 响应式数据
const analysisConfig = reactive({
  examinationId: null as number | null,
  classId: null as string | null,
  dimensions: ['score_distribution', 'class_comparison', 'trend_analysis']
})

const chartType = reactive({
  scoreDistribution: 'histogram',
  classComparison: 'bar',
  trendAnalysis: 'line',
  questionAnalysis: 'scoreRate',
  difficultyAnalysis: 'distribution'
})

const trendMetric = ref('average')

// 图表实例
let scoreDistributionChart: echarts.ECharts | null = null
let classComparisonChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null
let questionAnalysisChart: echarts.ECharts | null = null
let difficultyAnalysisChart: echarts.ECharts | null = null

// 数据
const examinationList = ref<Examination[]>([])
const classList = ref<string[]>([])
const analysisData = ref<any>(null)
const analysisLoading = ref(false)
const scoreStats = reactive({
  average: 0,
  median: 0,
  stdDeviation: 0,
  passRate: 0
})

const classComparisonData = ref<any[]>([])
const questionStats = reactive({
  totalQuestions: 0,
  averageCorrectRate: 0,
  hardestQuestion: '',
  easiestQuestion: ''
})

const difficultyStats = reactive({
  easy: 0,
  medium: 0,
  hard: 0,
  average: 0
})

// 导出
const showExportDialog = ref(false)
const exportLoading = ref(false)
const exportForm = reactive({
  format: 'pdf',
  includeContent: ['summary', 'charts', 'details'],
  title: '成绩分析报告'
})

// 获取考试列表
const fetchExaminationList = async () => {
  try {
    const response = await examApi.getExaminations({ page_size: 1000 })
    if (response.data?.results) {
      examinationList.value = response.data.results
    }
  } catch (error) {
    console.error('获取考试列表失败:', error)
    ElMessage.error('获取考试列表失败')
  }
}

// 获取班级列表
const fetchClassList = async () => {
  if (!analysisConfig.examinationId) return

  try {
    // 从成绩分析中获取班级列表
    const response = await gradingApi.getGradeAnalysis(analysisConfig.examinationId)
    if (response.data?.class_distribution) {
      classList.value = response.data.class_distribution.map((item: any) => item.class_name)
    }
  } catch (error) {
    console.error('获取班级列表失败:', error)
  }
}

// 获取成绩分析数据
const fetchAnalysisData = async () => {
  if (!analysisConfig.examinationId) {
    analysisData.value = null
    return
  }

  analysisLoading.value = true
  try {
    const response = await gradingApi.getGradeAnalysis(analysisConfig.examinationId)
    if (response.data) {
      analysisData.value = response.data

      // 如果选择了班级，过滤数据
      if (analysisConfig.classId) {
        filterDataByClass()
      }

      // 更新统计数据
      updateStatsFromAnalysis()

      await nextTick()
      initCharts()
    }
  } catch (error) {
    console.error('获取成绩分析数据失败:', error)
    ElMessage.error('获取成绩分析数据失败')
  } finally {
    analysisLoading.value = false
  }
}

// 按班级过滤数据
const filterDataByClass = () => {
  if (!analysisData.value || !analysisConfig.classId) return

  // 过滤班级数据
  const classData = analysisData.value.class_distribution.find(
    (item: any) => item.class_name === analysisConfig.classId
  )

  if (classData) {
    // 更新统计数据
    analysisData.value.statistics = {
      ...analysisData.value.statistics,
      total_students: classData.student_count,
      average_score: classData.average_score,
      pass_rate: classData.pass_rate
    }
  }
}

// 更新统计数据
const updateStatsFromAnalysis = () => {
  if (!analysisData.value?.statistics) return

  const stats = analysisData.value.statistics
  Object.assign(scoreStats, {
    average: Math.round(stats.average_score || 0),
    median: Math.round(stats.median_score || 0),
    stdDeviation: Math.round(stats.std_deviation || 0),
    passRate: Math.round(stats.pass_rate || 0)
  })

  // 更新班级对比数据
  if (analysisData.value.class_distribution) {
    classComparisonData.value = analysisData.value.class_distribution.map((item: any) => ({
      className: item.class_name,
      studentCount: item.student_count,
      averageScore: Math.round(item.average_score),
      maxScore: Math.round(item.highest_score || 0),
      minScore: Math.round(item.lowest_score || 0),
      passRate: Math.round(item.pass_rate)
    }))
  }

  // 更新题目统计数据
  if (analysisData.value.question_analysis) {
    const questions = analysisData.value.question_analysis
    const totalQuestions = questions.length
    const averageCorrectRate = Math.round(
      questions.reduce((sum: number, q: any) => sum + q.correct_rate, 0) / totalQuestions
    )

    const hardestQuestion = questions.reduce((min: any, q: any) =>
      q.correct_rate < min.correct_rate ? q : min
    )
    const easiestQuestion = questions.reduce((max: any, q: any) =>
      q.correct_rate > max.correct_rate ? q : max
    )

    Object.assign(questionStats, {
      totalQuestions,
      averageCorrectRate,
      hardestQuestion: `题目${hardestQuestion.question.id}`,
      easiestQuestion: `题目${easiestQuestion.question.id}`
    })
  }

  // 更新难度统计
  if (analysisData.value.question_analysis) {
    const questions = analysisData.value.question_analysis
    const easy = questions.filter((q: any) => q.difficulty === 'easy').length
    const medium = questions.filter((q: any) => q.difficulty === 'medium').length
    const hard = questions.filter((q: any) => q.difficulty === 'hard').length

    Object.assign(difficultyStats, {
      easy: Math.round((easy / questions.length) * 100),
      medium: Math.round((medium / questions.length) * 100),
      hard: Math.round((hard / questions.length) * 100),
      average: Math.round(((easy + medium * 2 + hard * 3) / questions.length) * 33)
    })
  }
}

// 处理考试变化
const handleExamChange = () => {
  analysisConfig.classId = null
  fetchAnalysisData()
  fetchClassList()
}

// 处理班级变化
const handleClassChange = () => {
  fetchAnalysisData()
}

// 刷新分析
const refreshAnalysis = () => {
  fetchAnalysisData()
}

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    // 分数分布图
    initScoreDistributionChart()
    // 班级对比图
    initClassComparisonChart()
    // 趋势图
    initTrendChart()
    // 题目分析图
    initQuestionAnalysisChart()
    // 难度分析图
    initDifficultyAnalysisChart()
  })
}

// 初始化分数分布图
const initScoreDistributionChart = () => {
  const el = document.getElementById('scoreDistributionChart')
  if (!el) return

  scoreDistributionChart = echarts.init(el)
  updateScoreDistributionChart()
}

// 更新分数分布图
const updateScoreDistributionChart = () => {
  if (!scoreDistributionChart || !analysisData.value) return

  const data = analysisData.value.score_distribution || []

  let option: any = {
    title: {
      text: '分数分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        return `${params.name}: ${params.value}人 (${params.percentage}%)`
      }
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.range)
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [{
      name: '人数',
      type: 'bar',
      data: data.map(item => item.count),
      itemStyle: {
        color: (params: any) => {
          const colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de']
          return colorList[params.dataIndex % colorList.length]
        }
      }
    }]
  }

  if (chartType.scoreDistribution === 'pie') {
    option = {
      title: {
        text: '分数分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}% ({d}人)'
      },
      series: [{
        type: 'pie',
        radius: '60%',
        data: data.map(item => ({
          name: item.range,
          value: item.count
        }))
      }]
    }
  } else if (chartType.scoreDistribution === 'line') {
    option = {
      title: {
        text: '分数分布曲线',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: data.map(item => item.range)
      },
      yAxis: {
        type: 'value',
        name: '人数'
      },
      series: [{
        type: 'line',
        smooth: true,
        data: data.map(item => item.count),
        areaStyle: {}
      }]
    }
  }

  scoreDistributionChart.setOption(option)
}

// 初始化班级对比图
const initClassComparisonChart = () => {
  const el = document.getElementById('classComparisonChart')
  if (!el || chartType.classComparison === 'table') return

  classComparisonChart = echarts.init(el)
  updateClassComparisonChart()
}

// 更新班级对比图
const updateClassComparisonChart = () => {
  if (!classComparisonChart) return

  const data = classComparisonData.value

  if (chartType.classComparison === 'radar') {
    const option = {
      tooltip: {},
      legend: {
        data: data.map(item => item.className)
      },
      radar: {
        indicator: [
          { name: '平均分', max: 100 },
          { name: '最高分', max: 100 },
          { name: '及格率', max: 100 },
          { name: '最低分', max: 100 },
          { name: '标准差', max: 20 }
        ]
      },
      series: [{
        type: 'radar',
        data: data.map(item => [
          item.averageScore,
          item.maxScore,
          item.passRate,
          100 - item.minScore,
          10 // 假设标准差
        ])
      }]
    }
    classComparisonChart.setOption(option)
  } else {
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: data.map(item => item.className)
      },
      xAxis: {
        type: 'category',
        data: data.map(item => item.className)
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '平均分',
          type: 'bar',
          data: data.map(item => item.averageScore)
        },
        {
          name: '最高分',
          type: 'bar',
          data: data.map(item => item.maxScore)
        },
        {
          name: '最低分',
          type: 'bar',
          data: data.map(item => item.minScore)
        }
      ]
    }
    classComparisonChart.setOption(option)
  }
}

// 初始化趋势图
const initTrendChart = () => {
  const el = document.getElementById('trendChart')
  if (!el) return

  trendChart = echarts.init(el)
  updateTrendChart()
}

// 更新趋势图
const updateTrendChart = () => {
  if (!trendChart) return

  const data = analysisData.value.trendData || []
  const metricKey = trendMetric.value as 'average' | 'passRate' | 'stdDeviation'
  const metricName = {
    average: '平均分',
    passRate: '及格率',
    stdDeviation: '标准差'
  }[metricKey]

  const option = {
    title: {
      text: `${metricName}趋势`,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.month)
    },
    yAxis: {
      type: 'value',
      name: metricName
    },
    series: [{
      name: metricName,
      data: data.map(item => item[metricKey]),
      smooth: true,
      type: chartType.trendAnalysis === 'area' ? 'line' : 'bar',
      areaStyle: chartType.trendAnalysis === 'area' ? {} : undefined
    }]
  }

  trendChart.setOption(option)
}

// 初始化题目分析图
const initQuestionAnalysisChart = () => {
  const el = document.getElementById('questionAnalysisChart')
  if (!el) return

  questionAnalysisChart = echarts.init(el)
  updateQuestionAnalysisChart()
}

// 更新题目分析图
const updateQuestionAnalysisChart = () => {
  if (!questionAnalysisChart || !analysisData.value) return

  const data = analysisData.value.question_analysis || []
  const metricKey = chartType.questionAnalysis as 'scoreRate' | 'errorRate' | 'timeSpent'
  const metricName = {
    scoreRate: '得分率',
    errorRate: '错误率',
    timeSpent: '平均用时(秒)'
  }[metricKey]

  const option = {
    title: {
      text: `${metricName}分析`,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        return `${params.name}: ${params.value}${metricKey === 'timeSpent' ? '秒' : '%'}`
      }
    },
    xAxis: {
      type: 'category',
      data: data.slice(0, 10).map(item => `题目${item.question.id}`)
    },
    yAxis: {
      type: 'value',
      name: metricName
    },
    series: [{
      type: 'bar',
      data: data.slice(0, 10).map(item => metricKey === 'scoreRate' ? item.correct_rate : metricKey === 'errorRate' ? (100 - item.correct_rate) : 0),
      itemStyle: {
        color: (params: any) => {
          const value = params.value
          if (metricKey === 'scoreRate') {
            return value >= 80 ? '#67c23a' : value >= 60 ? '#e6a23c' : '#f56c6c'
          } else if (metricKey === 'errorRate') {
            return value <= 5 ? '#67c23a' : value <= 15 ? '#e6a23c' : '#f56c6c'
          } else {
            return '#409eff'
          }
        }
      }
    }]
  }

  questionAnalysisChart.setOption(option)
}

// 初始化难度分析图
const initDifficultyAnalysisChart = () => {
  const el = document.getElementById('difficultyAnalysisChart')
  if (!el) return

  difficultyAnalysisChart = echarts.init(el)
  updateDifficultyAnalysisChart()
}

// 更新难度分析图
const updateDifficultyAnalysisChart = () => {
  if (!difficultyAnalysisChart || !analysisData.value) return

  // 从题目分析数据中计算难度分布
  const questions = analysisData.value.question_analysis || []
  const easy = questions.filter((q: any) => q.difficulty === 'easy').length
  const medium = questions.filter((q: any) => q.difficulty === 'medium').length
  const hard = questions.filter((q: any) => q.difficulty === 'hard').length

  const data = { easy, medium, hard }

  if (chartType.difficultyAnalysis === 'pie') {
    const option = {
      title: {
        text: '题目难度分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}%'
      },
      series: [{
        type: 'pie',
        radius: ['40%', '70%'],
        data: [
          { value: data.easy, name: '简单' },
          { value: data.medium, name: '中等' },
          { value: data.hard, name: '困难' }
        ]
      }]
    }
    difficultyAnalysisChart.setOption(option)
  } else if (chartType.difficultyAnalysis === 'heatmap') {
    // 热力图需要更复杂的数据结构，这里简化处理
    const option = {
      title: {
        text: '题目难度热力图',
        left: 'center'
      },
      tooltip: {
        position: 'top'
      },
      xAxis: {
        type: 'category',
        data: ['简单', '中等', '困难']
      },
      yAxis: {
        type: 'category',
        data: ['单选题', '多选题', '判断题', '填空题', '简答题']
      },
      visualMap: {
        min: 0,
        max: 100,
        calculable: true,
        inRange: {
          visualDimension: 2,
        }
      },
      series: [{
        name: '题目难度',
        type: 'heatmap',
        data: [
          [0, 0, 10], [0, 1, 15], [0, 2, 8], [0, 3, 12], [0, 4, 5],
          [1, 0, 8], [1, 1, 12], [1, 2, 15], [1, 3, 10], [1, 4, 6],
          [2, 0, 5], [2, 1, 10], [2, 2, 20], [2, 3, 8], [2, 4, 3]
        ]
      }]
    }
    difficultyAnalysisChart.setOption(option)
  } else {
    const option = {
      title: {
        text: '难度分布对比',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      xAxis: {
        type: 'category',
        data: ['简单', '中等', '困难']
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        name: '题目数量',
        type: 'bar',
        data: [data.easy, data.medium, data.hard]
      }]
    }
    difficultyAnalysisChart.setOption(option)
  }
}

// 处理分析变化
const handleAnalysisChange = () => {
  fetchAnalysisData()
}

// 更新所有图表
const updateAllCharts = () => {
  updateScoreDistributionChart()
  updateClassComparisonChart()
  updateTrendChart()
  updateQuestionAnalysisChart()
  updateDifficultyAnalysisChart()
}

// 获取及格率颜色
const getPassRateColor = (passRate: number) => {
  if (passRate >= 90) return '#67c23a'
  if (passRate >= 80) return '#409eff'
  if (passRate >= 60) return '#e6a23c'
  return '#f56c6c'
}

// 导出分析报告
const exportAnalysisReport = () => {
  showExportDialog.value = true
}

// 确认导出
const confirmExport = async () => {
  if (!analysisConfig.examinationId) {
    ElMessage.warning('请先选择考试')
    return
  }

  exportLoading.value = true
  try {
    await gradingApi.exportGrades({
      examination: analysisConfig.examinationId,
      format: exportForm.format as 'excel' | 'csv' | 'pdf'
    })
    ElMessage.success('分析报告导出成功')
    showExportDialog.value = false
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 页面挂载时
onMounted(async () => {
  await fetchExaminationList()
})
</script>

<style scoped lang="scss">
.grade-analysis {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 24px;

    .header-left {
      h1 {
        font-size: 28px;
        color: var(--el-text-color-primary);
        margin: 0 0 8px 0;
      }

      p {
        font-size: 14px;
        color: var(--el-text-color-regular);
        margin: 0;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .control-panel {
    margin-bottom: 24px;

    .panel-content {
      display: flex;
      gap: 24px;
      align-items: flex-start;

      .control-section {
        flex: 1;

        h4 {
          font-size: 14px;
          color: var(--el-text-color-primary);
          margin: 0 0 12px 0;
        }
      }
    }
  }

  .analysis-content {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
    gap: 24px;

    .analysis-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        h3 {
          font-size: 16px;
          color: var(--el-text-color-primary);
          margin: 0;
        }

        .chart-actions {
          display: flex;
          gap: 8px;
        }
      }

      .chart-container {
        height: 400px;
        margin-bottom: 16px;
      }

      .chart-stats {
        display: flex;
        justify-content: space-around;

        .stat-item {
          text-align: center;

          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: var(--el-text-color-primary);
            margin-bottom: 4px;
          }

          .stat-label {
            font-size: 12px;
            color: var(--el-text-color-regular);
          }
        }
      }

      .class-comparison-table {
        max-height: 400px;
        overflow: auto;
        margin-top: 16px;
      }
    }
  }

  .form-tip {
    font-size: 12px;
    color: var(--el-text-color-regular);
    margin-top: 4px;
  }

  .stat-value {
    font-weight: 500;
    color: var(--el-text-color-primary);
  }

  .stat-label {
    font-size: 12px;
    color: var(--el-text-color-regular);
  }

  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 400px;
  }

  .loading-state {
    padding: 20px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .grade-analysis {
    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;

      .header-right {
        justify-content: flex-start;
      }
    }

    .control-panel {
      .panel-content {
        flex-direction: column;
        gap: 16px;
      }
    }

    .analysis-content {
      grid-template-columns: 1fr;
    }
  }
}
</style>